import { Component, OnInit } from '@angular/core';
import { NavParams, AlertController,ViewController,NavController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { HTTP_SERVER_URL } from '../../app/app.contant';

@Component({
  templateUrl: 'cart.component.html',
  providers: []
})
export class CartPage implements OnInit {
  applies: Array<any> = [];
  selectedCount:number;

  constructor(
    private navParams: NavParams,
    private alertCtrl: AlertController,
    public viewCtrl: ViewController,
    public navCtrl:NavController,
    private http: HttpClient) {
    this.applies = this.navParams.get('applies');
    this.selectedCount = this.navParams.get('selectedCount');
  }

  ngOnInit() {

  }

  /** 提交采购申请*/
  submitApplay(applies) {
    return this.http.post(HTTP_SERVER_URL + 'home/law/material/submitapply', applies, { observe: 'response' })
        .map((resp) => resp.body['data'])
        .catch((error: any) => Observable.throw(error || 'Server error'));
  }

  /**数量增加 */
  increase(item) {
    if (item['materialCount'] < 99) {
      item['materialCount']++;
      this.selectedCount ++;
    }

  }
  /**数量减少 */
  decrease(item) {
    if (item['materialCount'] > 0) item['materialCount']--;
    if (item['materialCount'] == 0) {
      this.applies.forEach((e, idx) => {
        if (e['materialID'] == item['materialID']
          && e['materialIndexs'] == item['materialIndexs']) {
          this.applies.splice(idx, 1);
        }
      });
    }
    this.selectedCount --;
  }

  /**提交上报 */
  submit() {
    if (this.applies.length > 0) {
      let priceCount = 0, materialCount = 0;
      this.applies.forEach(item => {
        materialCount += item['materialCount'];
        priceCount += (item['materialCount'] * item['materialPrice']);
      });

      this.alertCtrl.create({
        message: '共选择'+materialCount+'件物品，总价￥'+priceCount+'元，您确定要提交申请吗？',
        buttons: [
          {
            text: '取消',
            handler: () => { }
          },
          {
            text: '确定',
            handler: () => {
              //提交保存
              this.submitApplay(this.applies).subscribe(data => {
                //关闭当前页
                this.viewCtrl.dismiss({});
              });
            }
          }

        ]
      }).present();
    }
  }

  dismiss(){
    let data = {'applies':this.applies};
    this.viewCtrl.dismiss(data);
  }
}
